package edu.ccut.saturn.studio.authority.wizard;

import java.io.File;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnProjectUtil;
import edu.ccut.saturn.studio.core.util.wizard.SaturnWizardPage;

public class AuthorityWizardPage extends SaturnWizardPage {
	public static final String AUTHORITY_FILE_NAME = "name"; //$NON-NLS-1$

	public static final String AUTHORITY_ELEMENT_NAME = "authority"; //$NON-NLS-1$
	private static final String CON_FILE_NAME = "/src/authority.config"; //$NON-NLS-1$
	private Text nameText;

	public AuthorityWizardPage() {
		setTitle(Messages.getString("AuthorityWizardPage.authorityconfig")); //$NON-NLS-1$
		setDescription(""); //$NON-NLS-1$
	}

	@Override
	public void initalValues(Map<String, Object> values) {
		values.put(AUTHORITY_FILE_NAME, this.nameText.getText().trim());
	}

	public void createControl(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		composite.setLayout(gridLayout);

		final Label label1 = new Label(composite, SWT.NONE);
		label1.setAlignment(SWT.RIGHT);
		label1.setText(Messages.getString("AuthorityWizardPage.name")); //$NON-NLS-1$

		nameText = new Text(composite, SWT.BORDER | SWT.READ_ONLY);
		final GridData gdnametext = new GridData(SWT.FILL, SWT.CENTER, true,
				false);
		nameText.setLayoutData(gdnametext);
		nameText.setText(AUTHORITY_ELEMENT_NAME);
		setControl(composite);
		validate();
	}

	/**
	 * 验证是否存在菜单管理的文件
	 */
	public boolean validate() {
		if (!validateProjectName()) {
			setErrorMessage(Messages
					.getString("AuthorityWizardPage.theprojectexistconfigfile")); //$NON-NLS-1$
			setPageComplete(false);
			return false;
		}
		setErrorMessage(null);
		setPageComplete(true);

		return true;
	}

	private boolean validateProjectName() {
		IProject iProject = SaturnProjectUtil.getProject(super.getSelection());
		String path = iProject.getLocation() + CON_FILE_NAME;
		IPath filePath = new Path(path);
		File file = filePath.toFile();
		if (file.exists()) {
			return false;
		}
		return true;
	}
}
